package com.ashes.brave.service.impl;

import com.ashes.brave.mapper.MenuSysMapper;
import com.ashes.brave.mapper.UserSysMapper;
import com.ashes.security.frame.LoginUser;
import com.ashes.oppo.po.SysAshesUserPO;
import com.ashes.oppo.vo.SysAshesUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserSysMapper userSysMapper;
    @Autowired
    private MenuSysMapper menuSysMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        SysAshesUserVO sysAshesUserVO = new SysAshesUserVO();
        sysAshesUserVO.setUserName(username);
        List<SysAshesUserPO> sysAshesUserPOS =userSysMapper.queryUserListData(sysAshesUserVO);
        //如果查询不到数据就通过抛出异常来给出提示
        if(CollectionUtils.isEmpty(sysAshesUserPOS)){
            throw new RuntimeException("用户名或密码错误");
        }
        //根据用户查询权限信息 添加到LoginUser中
        List<String> permsList = menuSysMapper.queryPermsByUserId(sysAshesUserPOS.get(0).getUserId());
        //封装成UserDetails对象返回
        return new LoginUser(sysAshesUserPOS.get(0),permsList);
    }
}